package com.example.apptest.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.app_test.R;
import com.example.apptest.events.EventTTSFinish;
import com.example.apptest.model.Word;
import com.example.apptest.utils.MQTTHelper;
import com.example.apptest.utils.PreferenceHelper;
import com.example.apptest.utils.SQLHelper;
import com.example.apptest.utils.TTSHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class WordFragment extends Fragment implements
        View.OnClickListener,
        AdapterView.OnItemSelectedListener,
        View.OnFocusChangeListener {

    int i=0;
    boolean on_off = false;
    int[] ico_id = {R.drawable.s_1, R.drawable.s_2, R.drawable.s_3, R.drawable.s_4,
            R.drawable.s_5,R.drawable.s_6, R.drawable.s_7, R.drawable.s_8};
    Handler handler;

    static private WordFragment instance = null;

    private TextView wordTv;
    private TextView transTv;
    private TextView startTv;
    private TextView endTv;
    private Spinner wordSp;
    private ImageView btnPlay;
    private boolean transOn = true;
    private boolean playing = false;

    private int gapMs;
    private int repeat;
    private int repeatCount = 0;

    private SeekBar seekBar;

    private WordFragment() {}
    static public WordFragment getInstance() {
        if(instance == null) {
            instance = new WordFragment();
        }
        return instance;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        instance = null;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_word, null);

        ImageView imgFg = view.findViewById(R.id.img_fg);

        view.findViewById(R.id.query).setOnClickListener(this);
        view.findViewById(R.id.btn_onoff).setOnClickListener(this);
        view.findViewById(R.id.btn_left).setOnClickListener(this);
        view.findViewById(R.id.btn_right).setOnClickListener(this);
        view.findViewById(R.id.btn_synthsize).setOnClickListener(this);
        btnPlay = view.findViewById(R.id.btn_play);
        btnPlay.setOnClickListener(this);
        view.findViewById(R.id.trans_onoff).setOnClickListener(this);

        startTv = view.findViewById(R.id.start_tv);
        endTv = view.findViewById(R.id.end_tv);
        startTv.setOnFocusChangeListener(this);
        endTv.setOnFocusChangeListener(this);

        startTv.setText(PreferenceHelper.getInstance().loadStartIdx().toString());
        endTv.setText(PreferenceHelper.getInstance().loadEndIdx().toString());

        wordSp = view.findViewById(R.id.word_spinner);
        wordSp.setOnItemSelectedListener(this);
        wordSp.setSelection(PreferenceHelper.getInstance().loadWordDB());

        wordTv = view.findViewById(R.id.word);
        transTv = view.findViewById(R.id.translation);
        seekBar = view.findViewById(R.id.seek_bar);
        wordTv.setOnClickListener(this);
        handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if(on_off)
                    imgFg.setImageResource(ico_id[i++%8]);
            }
        };

        Timer timer = new Timer();

        timer.schedule(  new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(5435);
            }
        } , 10, 60);

        EventBus.getDefault().register(this);
        gapMs = PreferenceHelper.getInstance().loadGap();
        repeat = PreferenceHelper.getInstance().loadRepeat();
        updateUI();
        return view;
    }
    private void updateUI() {
        if(wordIdx >= 0 && wordIdx < wordList.size()) {
            wordTv.setText(wordList.get(wordIdx).en);
            if(transOn)
                transTv.setText(wordList.get(wordIdx).getTranslation());
            else
                transTv.setText("");
        }
        seekBar.setMax(wordList.size()-1);
        seekBar.setProgress(wordIdx);
    }

    private int wordIdx = 0;
    private List<Word> wordList = new ArrayList<>();

    private boolean pageUpdate(int i) {
        boolean isEnd = false;
        wordIdx += i;
        if(wordIdx < 0 || wordIdx >= wordList.size()) {
            isEnd = true;
        }
        if(wordIdx > wordList.size() - 1) wordIdx = wordList.size() - 1;
        if(wordIdx<0) wordIdx = 0;
        updateUI();
        return isEnd;
    }
    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.query) {
            String db = wordSp.getSelectedItem().toString();
            if(startTv.getText().length()>0 && endTv.getText().length()>0) {
                wordList = SQLHelper.getInstance().query(db,
                        Integer.parseInt(startTv.getText().toString()),
                        Integer.parseInt(endTv.getText().toString()));
                wordIdx = 0;
                updateUI();
            }
        } else if (view.getId() == R.id.btn_onoff) {
            on_off = !on_off;
//            MQTTHelper.getInstance().publish("MQTT From Droid");
//            WSHelper.getInstance().sendMessage("WS From Droid");
            TTSHelper.getInstance().synthesize(wordListToString());
        } else if (view.getId() == R.id.btn_left) {
            pageUpdate(-1);
        } else if (view.getId() == R.id.btn_right) {
            pageUpdate(1);
        } else if (view.getId() == R.id.trans_onoff) {
            transOn = !transOn;
            updateUI();
        } else if(view.getId() == R.id.word) {
            playing = false;
            btnPlay.setImageResource(R.drawable.play);
            TTSHelper.getInstance().speak(wordTv.getText().toString());
        } else if(view.getId() == R.id.btn_play) {
            btnPlayClicked();
        } else if (view.getId() == R.id.btn_synthsize) {
            if(wordList.size() == 0) {
                Toast.makeText(getContext(), "请先查询", Toast.LENGTH_SHORT).show();
            } else {
                TTSHelper.getInstance().synthesize(wordListToString());
            }
        }
    }

    private void btnPlayClicked() {
        playing = !playing;
        repeatCount = 0;
        if(playing) {
            if(wordIdx == wordList.size() - 1) {
                wordIdx = 0;
                updateUI();
            }
            TTSHelper.getInstance().speak(wordTv.getText().toString());
        }
        btnPlay.setImageResource(playing ? R.drawable.pause : R.drawable.play);
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        PreferenceHelper.getInstance().saveWordDB(i);
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {}

    @Override
    public void onFocusChange(View view, boolean b) {
        if(view.getId() == R.id.start_tv) {
            int val = 0;
            if(startTv.getText().length()>0)
                val = Integer.parseInt(startTv.getText().toString());
            PreferenceHelper.getInstance().saveStartIdx(val);
        } else if(view.getId() == R.id.end_tv) {
            int val = 0;
            if(endTv.getText().length()>0)
                val = Integer.parseInt(endTv.getText().toString());
            PreferenceHelper.getInstance().saveEndIdx(val);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTTSFinish(EventTTSFinish event) {
        if(event.msg.length() > 0) {
            Toast.makeText(getContext(), "合成完毕:"+event.msg, Toast.LENGTH_SHORT).show();
            return;
        }
        if(playing == false)
            return;
        startTv.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (repeatCount++ == repeat-1) {
                    repeatCount = 0;
                    if(pageUpdate(1)) {
                        btnPlayClicked();
                        return;
                    }
                }
                if(wordIdx < wordList.size()) {
                    TTSHelper.getInstance().speak(wordList.get(wordIdx).en);
                }
            }
        }, gapMs);
    }

    private String wordListToString() {
        String res = "";
        for (Word w: wordList) {
            res += w.en + ";;;";
        }
        return res;
    }
}